#include <iostream>
#include <fstream>
#include <windows.h>

using namespace std;
const string lineTxt = " - c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024 ++++ c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024";

//  文本写入文件
streampos stringWriteToFile();


int main() {
    DWORD startSec = GetTickCount();
    streampos totalWriteSize = 0;
    for (int i = 0; i < 10; i++) {
       totalWriteSize= stringWriteToFile();
    }

    DWORD useMillionSecond = (GetTickCount() - startSec) / 10;
    cout << "文件写入完毕,文件总大小：" << totalWriteSize << " ，平均单次耗时(ms):" << useMillionSecond << endl;
    return 0;
}


//  文本写入文件
streampos  stringWriteToFile() {
    wstring filePath = L"D:/写文件/log_cpp_no_buffer.txt";
    int rows = 1000000;      // 写入100万行文本，模拟写入日志场景
    fstream fs(filePath.c_str(), ios::out | ios::trunc|ios::binary );
    if (!fs) {
        cerr << "创建文件出错" << endl;
        return 0;
    } else {
        string tmp = "";
        for (int i = 1; i <= rows; i++) {
            tmp = to_string(i) + lineTxt + "\n";
            fs.write(tmp.c_str(), tmp.length());
        }
        fs.seekg(0, ios::end);
        streampos  totalWriteSize = fs.tellg();
        fs.close();
        return totalWriteSize;
    }
}